class Snake{
    element:HTMLElement
    head:HTMLElement
    bodies:HTMLCollection

    // 宽度除以十后的数据，宽高的最大值，用以判断蛇是否撞墙
    maxWidth: number


    constructor(maxWidth:number = 290){
        this.maxWidth = maxWidth

        this.element = document.getElementById('snake') as HTMLElement
        this.head = document.querySelector('#snake > div') as HTMLElement
        this.bodies = this.element.getElementsByTagName('div')
    }
    // 蛇的移动
    get step(){
        return 10
    }
    // 蛇头的位置
    get X(){
        return this.head.offsetLeft
    }

    get Y(){
        return this.head.offsetTop
    }
    // 设置蛇头的位置
    set X(value:number){
        // 如果位置没动什么也不动
        if( value == this.X){
            return
        }
        // 如果位置超出范围，则报错
        if( value < 0 || value > this.maxWidth){
            throw new Error('蛇撞墙了。。。')
            
        }
        // 判断蛇掉头，不让其掉头
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value ){
            if(value > this.X){
                value = this.X - this.step
            }else{
                value = this.X + this.step
            }
        }
        // 蛇移动身体
        this.moveBodies()
        // 蛇头移动
        this.head.style.left = value + 'px'
        // 检查头尾相撞否
        this.checkHead()
    }

    set Y(value:number){
        if( value == this.Y){
            return
        }
        if( value < 0 || value > this.maxWidth){
            throw new Error('蛇撞墙了。。。')
            
        }

        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value){
            if(value > this.Y){
                value = this.Y - this.step
            }else{
                value = this.Y + this.step
            }
        }

        this.moveBodies()

        this.head.style.top = value + 'px'

        this.checkHead()
    }
    // 增加蛇的身体
    addBodies(){
        this.element.insertAdjacentHTML("beforeend","<div></div>")
    }
    // 移动蛇的身体，蛇头的单独设置的，先从最后一个往前移
    moveBodies(){
        for(let i=this.bodies.length-1;i > 0;i--){
            let body = this.bodies[i] as HTMLElement
            let x = (this.bodies[i-1] as HTMLElement).offsetLeft
            let y = (this.bodies[i-1] as HTMLElement).offsetTop
            body.style.left = x + 'px'
            body.style.top = y + 'px'
        }
    }
    // 检查是否头尾相撞
    checkHead(){
        for(let i = 1;i<this.bodies.length;i++){
            let bd = this.bodies[i] as HTMLElement
            if(this.X === bd.offsetLeft && this.Y === bd.offsetTop){
                throw new Error('头尾相撞---')
            }
        }
    }
}

export default Snake